import { useQueryClient } from "@tanstack/react-query";
import { ChevronsUpDown, UserCogIcon, UserIcon } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuShortcut,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "@/components/ui/sidebar";
import { authClient, type Session } from "@/lib/auth-client";
import { type OrgWithMembers, sessionQueryOptions } from "@/queries/auth";
import { Avatar, AvatarFallback } from "./ui/avatar";

export function OrgSwitcher({ session, orgs }: { session: Session; orgs: OrgWithMembers[] }) {
  const data = orgs.map((org) => ({
    id: org.id,
    name: org.name,
    role: org.members.find((member) => member.userId === session.user.id)?.role,
  }));
  const activeOrganization = data.find((org) => org.id === session.session.activeOrganizationId);
  const queryClient = useQueryClient();
  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              size="lg"
              className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
            >
              <Avatar className="rounded-lg">
                <AvatarFallback className="size-8 rounded-lg font-bold">
                  {activeOrganization?.name.charAt(0).toUpperCase()}
                </AvatarFallback>
              </Avatar>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">{activeOrganization?.name}</span>
                <span className="truncate text-xs uppercase">{activeOrganization?.role}</span>
              </div>
              <ChevronsUpDown className="ml-auto" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            className="w-(--radix-dropdown-menu-trigger-width) min-w-52 rounded-lg"
            align="start"
            side="bottom"
            sideOffset={4}
          >
            <DropdownMenuLabel className="text-muted-foreground text-xs">
              Organizations
            </DropdownMenuLabel>
            {data.map((org) => (
              <DropdownMenuItem
                key={org.id}
                onClick={async () => {
                  await authClient.organization.setActive({
                    organizationId: org.id,
                  });
                  queryClient.invalidateQueries({ queryKey: sessionQueryOptions.queryKey });
                }}
                className="gap-2 p-2"
              >
                <Avatar className="size-6 rounded-md">
                  <AvatarFallback className="rounded-md font-semibold">
                    {org.name.charAt(0).toUpperCase()}
                  </AvatarFallback>
                </Avatar>
                {org.name}
                <DropdownMenuShortcut className="flex items-center gap-1">
                  {org.role === "member" ? <UserIcon /> : <UserCogIcon />}
                </DropdownMenuShortcut>
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  );
}
